package my.mark.mybaibaoxiang.juc.biji07.Atomic;

import my.mark.mybaibaoxiang.juc.biji07.utils.UnsafeInstance;
import sun.misc.Unsafe;

/**
 * @author wxming.
 * @description: 模仿自定义一个Atomic类，对某个属性进行原子修改。
 */
public class AtomicStudentAgeUpdater {
    private String name;
    private volatile int age;

    private static final Unsafe unsafe = UnsafeInstance.reflectGetUnsafe();
    private static final long valueOffset;//偏移量：new出来的实例对象在内存中占了一块区域，起始到结束。偏移量就是age这个属性从起始位置开试找起找到age属性的内存距离，相对起始的内存地址。见图示意。

    static {
        try {//静态代码块里初始化
            valueOffset = unsafe.objectFieldOffset(AtomicStudentAgeUpdater.class.getDeclaredField("age"));
            System.out.println("valueOffset:--->" + valueOffset);
        } catch (Exception e) {
            throw new Error(e);
        }
    }

    //比较并且交换。
    public void compareAndSwapAge(int old, int target) {
        unsafe.compareAndSwapInt(this, valueOffset, old, target);
    }


    public AtomicStudentAgeUpdater(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public int getAge() {
        return this.age;
    }

    public static void main(String[] args) {
        AtomicStudentAgeUpdater updater = new AtomicStudentAgeUpdater("杨过", 18);
        updater.compareAndSwapAge(18, 56);

        System.out.println("真实的杨过年龄---" + updater.getAge());

    }
}
